package co.angluzha.commons.web.exception;

import co.angluzha.commons.base.result.Codes;
import co.angluzha.commons.base.result.R;
import co.angluzha.commons.base.result.Rt;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.adapter.AdvisorAdapter;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * co.angluzha.commons.web.exception文档说明
 *
 * @author Angluzha
 * @version 2022/11/21
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler implements ResponseBodyAdvice<R> {

    @ExceptionHandler(BindException.class)
    public R BindError(BindException e){
        List<String> msgs= e.getAllErrors()
                            .stream()
                            .map(error->error.getDefaultMessage())
                            .collect(Collectors.toList());
        return Rt.error(Codes.FAIL,msgs);
    }

    @ExceptionHandler
    public R error(Exception e){
        e.printStackTrace();
        log.error(e.getMessage());
        return Rt.error();
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.getMethod().getReturnType() == R.class;
    }

    @Override
    public R beforeBodyWrite(R r, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (!Codes.SUCCESS.getCode().equals(r.getCode())){
            serverHttpResponse.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return r;
    }
}
